package com.bdd.crowd.utils;

import com.bdd.crowd.constant.CrowdConstant;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author banddong
 * @create 2020-08-20 23:26
 * 通用方法工具类
 */
public class CrowdUtil {

    /**
     * 判定请求类型
     * @param request
     * @return
     */
    public static boolean judgeRequestType(HttpServletRequest request){
        // 1.获取请求请求头详细
        String accept = request.getHeader("Accept");
        String xRequested = request.getHeader("X-Requested-With");
        // 2.判断 true 是Ajax请求，false不是Ajax请求
        return  (accept != null && accept.contains("application/json"))
                ||
                (xRequested != null && xRequested.equals("XMLHttpRequest"));
    }

    /**
     * MD5加密
     * @param source 传入的明文字符串
     * @return encoded 加密结果
     */
    public static String md5(String source ){

        // 1.判断source是否有效
        if(source == null && source.length() == 0){
            // 2.字符串无效抛出异常
            throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }

        try {
            // 3.获取MessageDigets加密对象
            String algorithm = "md5";
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);

            // 4.获取明文字符串对应的字节数组
            byte[] input = source.getBytes();

            // 5.执行加密
            byte[] output = messageDigest.digest(input);

            // 6.创建BigInteger对象
            int signum = 1;
            BigInteger bigInteger = new BigInteger(signum, output);

            // 7.按照16进制将BigInteger的值转为字符串  加上toUpperCase()字母大写
            int radix = 16;
            String encoded = bigInteger.toString(radix).toUpperCase();

            return encoded;

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }














}
